package com.flyxiaozhu.erp.admin.authorize;

import com.flyxiaozhu.erp.core.entities.AdminUser;
import com.flyxiaozhu.erp.core.entities.Permission;
import com.flyxiaozhu.erp.core.repositories.AdminUserRepository;
import com.flyxiaozhu.erp.core.repositories.PermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class AdminUserDetailsService implements UserDetailsService {
    @Autowired
    AdminUserRepository adminUserRepository;

    @Autowired
    PermissionRepository permissionRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AdminUser user = adminUserRepository.findAdminUserByUsername(username);
        if (user != null) {
            List<Permission> permissions = permissionRepository.findByAdminUserId(user.getId());
            Set<GrantedAuthority> authorities = new HashSet<>();
            for (Permission permission : permissions) {
                if (permission != null && permission.getName() != null) {

                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_" + permission.getIdentity());
                    authorities.add(grantedAuthority);
                }
            }
            return new AdminUserDetails(user, authorities);
        } else {
            throw new UsernameNotFoundException("admin: " + username + " do not exist!");
        }
    }
}
